package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.LoginUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 通用实物商品列表
 */
public class CmnProductionListActivity extends BaseActivity {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.layout_default)
    LinearLayout layoutDefault;
    @Bind(R.id.layout_price)
    LinearLayout layoutPrice;
    @Bind(R.id.layout_sales)
    LinearLayout layoutSales;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;

    private ArrayList<Blog> blogs = new ArrayList<>();
    private CmnProductionAdapter adapter;
    private User user;
    private LoginUtil.LoginCallBack loginCallBack;
    private String keytype = "8";//类型	1:粮票超值;    2:有机商品    3:田家商品    4:地标商品    5:村游商品    6:唠嗑帖子
    //7:农货日志    8:粮库商品    9:乐乐商品    10:走走相关    11:特产商品    12:苗木    13:花卉    14:家电    15:日用品
    //16:粮库商家商品    17:农需商品
    private String keyid = "无";
    private String orderby = "1";//1：智能排序    2：热销    3：好评    4：唠嗑排序    5：时间排序    6：价格排序
    private String ordertype = "1";//1:降序；2:升序
    private String keyword = "";//搜索关键字	可选传参数，需要时传递;keytype=3时传商品类型名称
    private String saleflag = "";//农货状态	只有keytype=3时需要传递该参数；0：关闭；1：进行中
    private String topflag	 = "";//推荐/热门景点标志	topflag=1，可选传参数，keytype=2,3,4,8,9，16时可传
    private String cheapflag = "";//低价抢购标志	cheapflag=1，可选传参数，只有keytype=9时可传
    private String score_percent = "";//粮票占比	5-9的整数，可选传参数，只有keytype=8时可传
    private String seller_id = "";//卖家id	可选传参数，keyytype=4,5,9,10,11可传
    private String lng = "";//可选传参数，需要时传递
    private String lat = "";//纬度	可选传参数，需要时传递
    private String district_name = "";//地区	可选传参数，用于获取周边农需商品
    private int page = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_cmn_productions_list);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        EventBus.getDefault().register(this);
        refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void getExras() {
        keytype = mIntent.getStringExtra("keytype");
        keyid = mIntent.getStringExtra("keyid");
        keyword = mIntent.getStringExtra("keyword");
        saleflag = mIntent.getStringExtra("saleflag");
        topflag = mIntent.getStringExtra("topflag");
        cheapflag = mIntent.getStringExtra("cheapflag");
        score_percent = mIntent.getStringExtra("score_percent");
        seller_id = mIntent.getStringExtra("seller_id");
        district_name = mIntent.getStringExtra("district_name");
    }

    @Override
    protected void setListener() {
        titleRightBtn.setVisibility(View.GONE);
        titleText.setText(mIntent.getStringExtra("title"));
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().blogList(keytype, keyid, orderby, ordertype, keyword,
                        saleflag, topflag, cheapflag, score_percent, seller_id, lng, lat, district_name, "", page+"");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().blogList(keytype, keyid, orderby, ordertype, keyword,
                        saleflag, topflag, cheapflag, score_percent, seller_id, lng, lat, district_name, "", page+"");
            }
        });
    }

    @OnClick({R.id.title_left_btn, R.id.layout_default, R.id.layout_price, R.id.layout_sales})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_default:
                if (orderby.equals("1")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutDefault.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "1";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_price:
                if (orderby.equals("6")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutPrice.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "6";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_sales:
                if (orderby.equals("2")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutSales.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "2";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case CART_ADD:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case CART_ADD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                ArrayList<Blog> goods = bResult.getObjects();
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    refreshLoadmoreLayout.setLoadmoreable(true);
                    blogs.clear();
                    blogs.addAll(goods);
                } else {//加载更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (goods.size() > 0) {
                        blogs.addAll(goods);
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "成功添加到购物车");
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "添加到购物车失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshData(failedType);
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "添加到购物车失败");
                break;
        }
    }

    private void refreshData(int failedType) {
        if (null == adapter) {
                adapter = new CmnProductionAdapter(mContext, blogs);
                adapter.setItemClickListener(new OnBlogItemClickListener() {
                    @Override
                    public void onClickListener(int position) {
                        Intent it = BaseUtil.createBlogIntent(mContext, blogs.get(position).getType());
                        it.putExtra("blog_id", blogs.get(position).getId());
                        mContext.startActivity(it);
                    }

                    @Override
                    public void onCartListener(final int position) {
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                getNetWorker().cartAdd(user.getToken(), blogs.get(position).getId(), "1", "0");
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }
                });
            adapter.setEmptyString("暂无商品");
            listview.setAdapter(adapter);
        } else {
            adapter.setEmptyString("暂无商品");
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failedType);
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }

}
